package com.wuyan.locationdog.ui.compass

import android.graphics.Color
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.AMapUtils
import com.amap.api.maps.model.LatLng
import com.arcsoft.commonbase.base.BaseBindingFragment
import com.arcsoft.commonbase.bean.DeviceBeanContent
import com.arcsoft.commonbase.bus.Bus
import com.arcsoft.commonbase.bus.bus_device_info_modify
import com.arcsoft.commonbase.bus.bus_team_click
import com.arcsoft.commonbase.bus.bus_team_refresh
import com.arcsoft.commonbase.ext.invisible
import com.arcsoft.commonbase.ext.loadImageCircleCar
import com.arcsoft.commonbase.ext.visible
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.TimeUtils
import com.wuyan.locationdog.R
import com.wuyan.locationdog.adapter.ImageAdapter
import com.wuyan.locationdog.databinding.CompassFragmentBinding
import com.wuyan.locationdog.help.DeviceHelp
import com.wuyan.locationdog.help.LoginHelp
import com.wuyan.locationdog.help.getKmOrM
import com.wuyan.locationdog.util.maputil.MapHelp
import com.wuyan.locationdog.util.maputil.MapUtil
import com.wuyan.locationdog.view.TipPopup2
import com.wuyan.locationdog.viewmodel.DeviceViewModel
import com.youth.banner.config.IndicatorConfig
import com.youth.banner.indicator.CircleIndicator
import com.youth.banner.listener.OnPageChangeListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Timer
import java.util.TimerTask
import kotlin.math.absoluteValue


class CompassFragment : BaseBindingFragment<CompassFragmentBinding>() {
    private var lastTime: Long = 0L
    private var teamId: String = ""
    private var mDeviceBeanContent: DeviceBeanContent? = null
    private var first: DeviceBeanContent? = null
    private var hasLoadedKm: Boolean = false
    private var compassDegrees: Int = 0
    private var angle: Double = 0.0
    private var lastDegrees: Int = 0
    private val mViewModel: DeviceViewModel by viewModels()
    private var sensorManager: SensorManager? = null

    private val sensorEventListener: SensorEventListener = object : SensorEventListener {
        var gravity = FloatArray(3)
        var geomagnetic = FloatArray(3)
        override fun onSensorChanged(event: SensorEvent) {
            if (event.sensor.type == Sensor.TYPE_ACCELEROMETER) {
                System.arraycopy(event.values, 0, gravity, 0, 3)
            } else if (event.sensor.type == Sensor.TYPE_MAGNETIC_FIELD) {
                System.arraycopy(event.values, 0, geomagnetic, 0, 3)
            }
            val rotationMatrix = FloatArray(9)
            val success = SensorManager.getRotationMatrix(rotationMatrix, null, gravity, geomagnetic)
            if (success) {
                val orientation = FloatArray(3)
                SensorManager.getOrientation(rotationMatrix, orientation)
                val azimuth = orientation[0]
                var degrees = Math.toDegrees(azimuth.toDouble()).toFloat()
                degrees = (degrees + 360) % 360 // 保证角度范围在0-360度之间
                // 显示指南针角度
                binding.apply {
                    compassDegrees = degrees.toInt()
                    val absoluteValue = (compassDegrees - lastDegrees).absoluteValue
                    if (absoluteValue <= 1 || absoluteValue == 359) {
                        return
                    }
                    if (TimeUtils.getNowMills() - lastTime < 120) {
                        return
                    }
                    lastTime = TimeUtils.getNowMills()

                    lastDegrees = compassDegrees
                    var fangxiang = "北"
                    when (compassDegrees) {
                        0 -> {
                            fangxiang = "北"
                        }

                        in 1..89 -> {
                            fangxiang = "东北"
                        }

                        90 -> {
                            fangxiang = "东"
                        }

                        in 91..179 -> {
                            fangxiang = "东南"
                        }

                        180 -> {
                            fangxiang = "南"
                        }

                        in 181..269 -> {
                            fangxiang = "西南"
                        }

                        270 -> {
                            fangxiang = "西"
                        }

                        in 271..359 -> {
                            fangxiang = "西北"
                        }
                    }

                    tvDegrees.text = fangxiang + compassDegrees.toString() + "°"
                    ivCompass.rotation = (-compassDegrees).toFloat()
                    dogAngle()
                }


            }
        }

        override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {
            // do nothing
        }
    }

    //声明定位回调监听器
    private var mLocationListener = AMapLocationListener { amapLocation ->
        if (amapLocation != null) {
            if (amapLocation.errorCode == 0) {
                //实时位置上报
                Log.e("map", "定位成功:$amapLocation")
                val phonelatLng = LatLng(amapLocation.latitude, amapLocation.longitude)
                MapHelp.phonelatLng = phonelatLng
                binding.distance(phonelatLng, mDeviceBeanContent)

            } else {

            }
        }
    }

    override fun lazyLoadData() {
        binding.apply {
            btnBack.setOnClickListener { mActivity.finish() }
            if (LoginHelp.isDeviceLogin) {
                btnBack.visible()
            }
            btnCmdVoiceDog.setOnClickListener {
                TipPopup2(mActivity,
                    R.mipmap.cmd_voice_dog_dialog,
                    "声音寻犬",
                    "是否立即下发声音寻回？",
                    "确定",
                    "取消",
                    {
                    }

                ).showPopupWindow()
            }
            btnCmdAlarmDog.setOnClickListener {
                TipPopup2(mActivity,
                    R.mipmap.cmd_alrm_dog_dialog,
                    "爆闪寻犬",
                    "是否立即下发爆闪寻犬？",
                    "确定",
                    "取消",
                    {
                    }

                ).showPopupWindow()
            }
            btnCmdRing.setOnClickListener {
                TipPopup2(mActivity,
                    R.mipmap.cmd_ring_dialog,
                    "铃声训练",
                    "是否立即下发铃声训练？",
                    "确定",
                    "取消",
                    {
                    }

                ).showPopupWindow()
            }
            btnCmdVibrate.setOnClickListener {
                TipPopup2(mActivity,
                    R.mipmap.cmd_vibrate_dialog,
                    "震动训练",
                    "是否立即下发震动训练？",
                    "确定",
                    "取消",
                    {
                    }

                ).showPopupWindow()
            }
            btnCmdElectric.setOnClickListener {
                TipPopup2(mActivity,
                    R.mipmap.cmd_electric_dialog,
                    "电击训练",
                    "是否立即下发电击训练？",
                    "确定",
                    "取消",
                    {
                    }

                ).showPopupWindow()
            }

        }


        // 实例化SensorManager
        sensorManager = mActivity.getSystemService(AppCompatActivity.SENSOR_SERVICE) as SensorManager

        // 注册SensorEventListener
        sensorManager!!.registerListener(
            sensorEventListener,
            sensorManager!!.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_NORMAL
        )
        sensorManager!!.registerListener(
            sensorEventListener,
            sensorManager!!.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
            SensorManager.SENSOR_DELAY_NORMAL
        )

        val timer = Timer()
        timer?.scheduleAtFixedRate(object : TimerTask() {
            override fun run() {
                lifecycleScope.launch(Dispatchers.Main) {
                    MapHelp.initLocation(mActivity, mLocationListener)
                }
            }
        }, 0, 10000) // 每秒更新一次


    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        loadData()
    }

    fun loadData() {
        teamId = ""
        val map = HashMap<String, Any>()
        map["pageSize"] = 9999
        map["pageNum"] = 1
        mViewModel.deviceList(map)
    }

    override fun onResume() {
        super.onResume()
        if (!hasLoadedKm) {
            binding.getKm(first)
        }
    }

    fun loadTeamDeviceList(teamId: String) {
        val map = HashMap<String, Any>()
        map["teamId"] = teamId
        mViewModel.teamDeviceList(map)
    }

    fun loadTeam() {
        val map = HashMap<String, Any>()
        map["pageSize"] = 9999
        map["pageNum"] = 1
        mViewModel.getTeamList(map)
    }

    override fun observe() {
        super.observe()
        Bus.observe<String>(bus_team_click, this) {
            teamId = it
            if (teamId.isNullOrEmpty()) {
                loadData()
            } else {
                loadTeamDeviceList(it)
            }
        }
        //团队
        Bus.observe<String>(bus_team_refresh, this) {
            loadTeam()
        }

        Bus.observe<String>(bus_device_info_modify, this) {
            if (teamId.isNullOrEmpty()) {
                loadData()
            } else {
                loadTeamDeviceList(it)
            }
        }

        //团队列表
        mViewModel.mTeamDetailList.observe(this) {
            val teamList = it?.content
            if (teamList?.find { it.teamId == teamId } == null) {
                if (teamId.isNotEmpty()) {
                    loadData()
                }
            } else {
                if (teamId.isNotEmpty()) {
                    loadTeamDeviceList(teamId)
                }
            }


        }
        mViewModel.error.observe(this) {
//            binding.includedEmpty.setEmptyViewConfig("网络异常", "请检查网络设置或稍后重试", com.arcsoft.commonbase.R.mipmap.empty_net) {
//                loadNetData()
//            }
        }

        mViewModel.deviceListBean.observe(this) {

            var mDatas = it.content?.toMutableList()
            if (LoginHelp.isDeviceLogin) {
                mDatas = mutableListOf(DeviceHelp.selectDeviceBeanContent)
            }

            binding.apply {
                if (mDatas.isNullOrEmpty()) {
                    bottomLayout.invisible()
                    deviceName.invisible()
                    banner.invisible()
                    headLayout.invisible()
                    mDeviceBeanContent = null
                } else {
                    bottomLayout.visible()
                    deviceName.visible()
                    banner.visible()
                    headLayout.visible()
                    first = mDatas?.get(0)


                    getKm(first)
                }
            }

            binding.banner.addBannerLifecycleObserver(viewLifecycleOwner)//添加生命周期观察者
                .setAdapter(ImageAdapter(mActivity, mDatas))
//            .setBannerRound2(SizeUtils.dp2px(8F).toFloat())
                .setBannerGalleryEffect(45, 16, 1F)
                .setIndicator(CircleIndicator(context))
                .setIndicatorSelectedColor(Color.WHITE)
                .setIndicatorNormalWidth(SizeUtils.dp2px(8F))
                .setIndicatorSelectedWidth(SizeUtils.dp2px(8F))
                .setIndicatorMargins(IndicatorConfig.Margins(SizeUtils.dp2px(2F)))
                .setOnBannerListener { data, position ->
                }
                .addOnPageChangeListener(object : OnPageChangeListener {
                    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

                    }

                    override fun onPageSelected(position: Int) {
                        binding.apply {
                            val first = mDatas?.get(position)
                            getKm(first)
                        }
                    }

                    override fun onPageScrollStateChanged(state: Int) {

                    }
                })
        }

    }

    private fun CompassFragmentBinding.getKm(first: DeviceBeanContent?) {
        mDeviceBeanContent = first
        deviceName.text = first?.let { it1 -> DeviceHelp.getDeviceName(it1) }
        ivHead.loadImageCircleCar(first?.dog?.dogImg)
        MapHelp.phonelatLng?.let {
            hasLoadedKm = true
            angle = MapUtil.calculateAngle(
                it.latitude,
                it.longitude,
                first?.gaoDeLat ?: 0.0,
                first?.gaoDeLng ?: 0.0,
            )
            distance(it, first)
            dogAngle()
        }
    }

    private fun CompassFragmentBinding.distance(
        it: LatLng,
        first: DeviceBeanContent?
    ) {
        val calculateLineDistance = AMapUtils.calculateLineDistance(
            it,
            LatLng(first?.gaoDeLat ?: 0.0, first?.gaoDeLng ?: 0.0)
        )
        km.text = getKmOrM(calculateLineDistance.toInt())
        if (first == null) {
            km.text = "0km"
        }
    }

    private fun CompassFragmentBinding.dogAngle() {
        headLayout.rotation = (angle + 360 - lastDegrees).toFloat()
    }

}